<template>
  <div>
    <!-- http-request为el-upload的上传属性，上传时调用 -->
    <el-upload list-type="picture-card" :limit="1" action="#" :on-preview="preview" :on-remove="handleRemove" :on-change="changeFile" :file-list="fileList" :class="{disabled:fileComputed}" :http-request="upload" :before-upload="beforeUpload">
      <i class="el-icon-plus" />
    </el-upload>
    <el-progress v-if="showPercent" style="width: 180px" :percentage="percent" />
    <el-dialog title="图片" :visible.sync="showDialog">
      <img :src="imgUrl" style="width:100%" alt="">
    </el-dialog>
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5'
const cos = new COS({
  SecretId: 'AKIDMXS6TeaFdlcCWbPwCBuMXQ3QWLyKQGqA',
  SecretKey: '4wYv2sRjlW1EBrGOFqACzVkjRVKs9AtL'
})
export default {
  data() {
    return {
      fileList: [], // 图片地址设置为数组
      showDialog: false, // 控制显示弹框
      imgUrl: '',
      currentFileUid: '', // 记录当前上传的图片id
      percent: 0,
      showPercent: false // 默认不显示进度条
    }
  },
  computed: {
    //  设定计算属性，判断是否已经上传完一张，限制图片数量的上传
    fileComputed() {
      return this.fileList.length === 1
    }
  },
  methods: {
    preview(file) {
      // 预览图片
      this.imgUrl = file.url
      this.showDialog = true
    },
    // 删除图片和添加图片
    handleRemove(file) {
      this.fileList = this.fileList.filter(item => item.uid !== file.uid)
    },
    // 修改文件触发
    changeFile(file, fileList) {
      this.fileList = fileList.map(item => item)
    },
    // 上传之前检查文件大小
    beforeUpload(file) {
      console.log(file)
      const types = ['image/jpg', 'image/gif', 'image/png', 'image/bmp', 'image/jpeg']
      if (!types.includes(file.type)) {
        this.$message.error('上传图片只能是JPG，GIF，BMP，PNG,JPEG格式！')
        return false
      }
      //   检查大小
      const maxSize = 5 * 1024 * 1024
      if (maxSize < file.size) {
        this.$message.error('图片大小最大不能超过5M')
        return false// 上传终止
      }
      //   确定当前上传的就是当前的这个file
      this.currentFileUid = file.uid
      this.showPercent = true
    },
    upload(params) {
    //   console.log(58, params)
      if (params.file) {
        // 执行上传操作
        cos.putObject({
          Bucket: 'hr-staffphoto-1308541681', // 存储桶名称
          Region: 'ap-guangzhou', // 地域
          Key: params.file.name, // 文件名
          Body: params.file, // 要上传的文件对象
          onProgress: (params) => {
            this.percent = params.percent * 100
          },
          StorageClass: 'STANDARD'// 上传的模式类型，默认标准类型
        }, (err, data) => {
          // data返回数据之后，应该怎么处理
        //   console.log(err || data)
          if (!err && data.statusCode === 200) {
            // 表示成功了
            console.log(87, this.fileList)
            console.log(this.currentFileUid)
            this.fileList = this.fileList.map(item => {
              if (item.uid === this.currentFileUid) {
                return { url: 'http://' + data.Location, upload: true } // 将本地的地址换成腾讯云地址
              }
              return item
            })
            setTimeout(() => {
              this.showPercent = false// 隐藏进度条
              this.percent = 0// 进度归0
            }, 2000)
          }
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .disabled .el-upload--picture-card {
  display: none
}
</style>

<style lang="scss">
  img {
    object-fit: cover;
  }
</style>

